package rsa;

import java.math.BigInteger;
import java.text.DecimalFormat;

public class Util {
	public static BigInteger gcd2(BigInteger a, BigInteger b) { //Greatest common divisor function for BigIntegers
		if (b.equals(BigInteger.ZERO))
			return a;
		else
			return gcd2(b, a.mod(b));
	}
	
	static BigInteger CalculateE(BigInteger fi) { //function calculating E value with fi input
		int found = 0;
		BigInteger E = new BigInteger("1000");
		
		while(found<2) {
			//System.out.println(E);
			E = E.add(BigInteger.ONE);
			if(gcd2(fi,E).equals(BigInteger.ONE)) {
				found++; 
			}
		}
		
		return E;
	}
	
	public int[] EE (int a, int b, int c, int d, int e, int f) {
		if (b==0) {
			int [] ret = {0,0,0};
			ret [0] = a; // gcd(a,b)
			ret [1] = e; // coefcient of a
			ret [2] = f; // coefcient of b
			return ret;
		} else {
			return EE(b, a%b, e-(a/b)*c, f-(a/b)*d, c, d);
		}
	}
	
	
	
	// FUNCTIONS FOR CONVERTING BIGINTEGERS AND STRINGS
	
	
	public static BigInteger convert(String message) { //convert ASCII to BIGINT (sets of 3 digit ascii values)
		String output = "126";
		BigInteger output2;
		
		for(int i=0;i<message.length();i++) {
			char letter = message.charAt(i);
			int letterVal = (int) letter;
			
			String letterStr = customAscii(letterVal);
			
			output = output+letterStr;
		}
		output2 = new BigInteger(output);
		return output2;
	}
	
	public static String customAscii(int value) { //function used in convert void
	      DecimalFormat myFormatter = new DecimalFormat("000");
	      String output = myFormatter.format(value);
	      return output;
	}
	
	public static String revert(BigInteger message) { //convert BIGINT to ASCII
		String outMsg = "";
		String strMsg = message.toString();
		for(int i=0;i<(strMsg.length());i=i+3) {
			int letter = Integer.parseInt(strMsg.substring(i, i+3));
			char letterChar = (char)letter;
			outMsg=outMsg+letterChar;
		}
		return outMsg;
	}
}
